# -*- coding: utf-8 -*-

"""Unimail
@version: 0.14
@license: GPL 3.0 (see "license" file)
@author: Jose A. Jimenez
@contact: jajimc@gmail.com"""

import sys
import os
import gtk
import core

DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))

class DialSettings:
    """Class that represents user e-mail account settings window."""

    def __init__(self, settings):
        if settings == None or not isinstance(settings, core.configuration.Settings):
            raise Exception("'settings' must be a 'Settings' object.")
            
        self.__gladefile = os.path.join(DIR, "dialsettings.glade")
        self.__builder = gtk.Builder()
        self.__builder.add_from_file(self.__gladefile)
        self.__dialog = self.__builder.get_object("dialSettings")
        
        self.__butOk = self.__builder.get_object("butOk")
        
        self.__entEmailAddress = self.__builder.get_object("entEmailAddress")
        self.__entEmailName = self.__builder.get_object("entEmailName")
        
        self.__entImapServer = self.__builder.get_object("entImapServer")
        self.__chkImapSsl = self.__builder.get_object("chkImapSsl")
        self.__entImapPort = self.__builder.get_object("entImapPort")
        self.__entImapUserId = self.__builder.get_object("entImapUserId")
        self.__entImapUserPassword = self.__builder.get_object("entImapUserPassword")
        self.__chkImapSavePassword = self.__builder.get_object("chkImapSavePassword")
        self.__spinDownloadRateMax = self.__builder.get_object("spinDownloadRateMax")
        self.__entInboxDirPath = self.__builder.get_object("entInboxDirPath")
        
        self.__entSmtpServer = self.__builder.get_object("entSmtpServer")
        self.__chkSmtpTls = self.__builder.get_object("chkSmtpTls")
        self.__entSmtpPort = self.__builder.get_object("entSmtpPort")
        self.__entSmtpUserId = self.__builder.get_object("entSmtpUserId")
        self.__entSmtpUserPassword = self.__builder.get_object("entSmtpUserPassword")
        self.__chkSmtpSavePassword = self.__builder.get_object("chkSmtpSavePassword")
        self.__spinSendRateMax = self.__builder.get_object("spinSendRateMax")
        self.__spinPartSize = self.__builder.get_object("spinPartSize")
        self.__spinPartWaitTime = self.__builder.get_object("spinPartWaitTime")
        self.__chkPartRandomWaitTime = self.__builder.get_object("chkPartRandomWaitTime")
                
        self.__defaultEntryTextColor = self.__entImapUserPassword.get_style().text[0]
                
        self.__builder.connect_signals(self)
        self.__load_settings(settings)
        self.__init_data()
        
    def __load_settings(self, settings):
        self.__entEmailAddress.set_text(settings.get_email_address())
        self.__entEmailName.set_text(settings.get_email_name())
        
        self.__entImapServer.set_text(settings.get_imap_server())
        self.__chkImapSsl.set_active(settings.is_imap_ssl_needed())
        self.__entImapPort.set_text(str(settings.get_imap_port()))
        self.__entImapUserId.set_text(settings.get_imap_user_id())
        imapUserPassword = settings.get_imap_user_password()
        self.__entImapUserPassword.set_text(imapUserPassword)
        self.__chkImapSavePassword.set_active(imapUserPassword != "")
        self.__entImapUserPassword.set_sensitive(imapUserPassword != "")
        
        self.__spinDownloadRateMax.set_value(settings.get_imap_download_rate_max())
        self.__entInboxDirPath.set_text(settings.get_inbox_dir_path())
        
        self.__entSmtpServer.set_text(settings.get_smtp_server())
        self.__chkSmtpTls.set_active(settings.is_smtp_tls_needed())
        self.__entSmtpPort.set_text(str(settings.get_smtp_port()))
        self.__entSmtpUserId.set_text(settings.get_imap_user_id())
        smtpUserPassword = settings.get_smtp_user_password()
        self.__entSmtpUserPassword.set_text(smtpUserPassword)
        self.__chkSmtpSavePassword.set_active(smtpUserPassword != "")
        self.__entSmtpUserPassword.set_sensitive(smtpUserPassword != "")
        
        self.__spinSendRateMax.set_value(settings.get_smtp_send_rate_max())
        self.__spinPartSize.set_value(settings.get_part_size())
        self.__spinPartWaitTime.set_value(settings.get_part_wait_time())
        self.__chkPartRandomWaitTime.set_active(settings.is_random_wait_time())
        
    def __clear_data(self):
        self.__entEmailAddress.set_text("")
        self.__entEmailName.set_text("")
        
        self.__entImapServer.set_text("")
        self.__chkImapSsl.set_active(True)
        self.__entImapPort.set_text("993")
        self.__entImapUserId.set_text("")
        self.__entImapUserPassword.set_text("")
        self.__spinDownloadRateMax.set_value(0)
        self.__entInboxDirPath.set_text(core.paths.DEFAULT_INBOX_DIR)
        
        self.__entSmtpServer.set_text("")
        self.__chkSmtpTls.set_active(True)
        self.__entSmtpPort.set_text("995")
        self.__entSmtpUserId.set_text("")
        self.__entSmtpUserPassword.set_text("")
        self.__spinSendRateMax.set_value(0)
        self.__spinPartSize.set_value(15)
        self.__spinPartWaitTime.set_value(0)
        self.__chkPartRandomWaitTime.set_active(False)
        
    def __init_data(self):
        self.__settings = None

    def run(self):
        self.__dialog.show_all()
        result = self.__dialog.run()
        
        if result == gtk.RESPONSE_OK:
            emailAddress = self.__entEmailAddress.get_text()
            emailName = self.__entEmailName.get_text()

            imapServer = self.__entImapServer.get_text()
            imapSsl = self.__chkImapSsl.get_active()
            imapPort = int(self.__entImapPort.get_text())
            imapUserId = self.__entImapUserId.get_text()
            imapUserPassword = self.__entImapUserPassword.get_text()
            downloadRateMax = self.__spinDownloadRateMax.get_value_as_int()
            inboxDirPath = self.__entInboxDirPath.get_text()

            smtpServer = self.__entSmtpServer.get_text()
            smtpTls = self.__chkSmtpTls.get_active()
            smtpPort = int(self.__entSmtpPort.get_text())
            smtpUserId = self.__entSmtpUserId.get_text()
            smtpUserPassword = self.__entSmtpUserPassword.get_text()
            smtpSendRateMax = self.__spinSendRateMax.get_value_as_int()      
            partSize = self.__spinPartSize.get_value_as_int()
            partWaitTime = self.__spinPartWaitTime.get_value_as_int()
            partRandomWaitTime = self.__chkPartRandomWaitTime.get_active()

            self.__settings = core.configuration.Settings(emailAddress, emailName,
            imapServer, imapSsl, imapPort, imapUserId, imapUserPassword, downloadRateMax, inboxDirPath,
            smtpServer, smtpTls, smtpPort, smtpUserId, smtpUserPassword, smtpSendRateMax, partSize, partWaitTime, partRandomWaitTime)
        
        self.__dialog.destroy()
        return result
        
    def get_settings(self):
        return self.__settings

    def butinboxdirpath_clicked(self, widget):
        dialog = gtk.FileChooserDialog(title="Choose the inbox directory", action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
        buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        
        response = dialog.run()
        
        if response == gtk.RESPONSE_OK:
            self.__entInboxDirPath.set_text(dialog.get_current_folder())
            
        dialog.destroy()
        
    def chkimapsavepassword_toggled(self, widget):
        save = self.__chkImapSavePassword.get_active()
        self.__entImapUserPassword.set_sensitive(save)
        
        if not save:
            self.__entImapUserPassword.set_text("")
    
    def chksmtpsavepassword_toggled(self, widget):
        save = self.__chkSmtpSavePassword.get_active()
        self.__entSmtpUserPassword.set_sensitive(save)
        
        if not save:
            self.__entSmtpUserPassword.set_text("")
            
    def data_changed(self, widget):
        emailAddress = self.__entEmailAddress.get_text()
        
        condition1 = (emailAddress == "" or core.validation.validate_email_address(emailAddress))
        condition2 = self.__entImapPort.get_text().isdigit()
        condition3 = self.__entSmtpPort.get_text().isdigit()
        
        if condition1:
            self.__entEmailAddress.modify_text(gtk.STATE_NORMAL, self.__defaultEntryTextColor)
        else:
            self.__entEmailAddress.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#FF0000"))
            
        if condition2:
            self.__entImapPort.modify_text(gtk.STATE_NORMAL, self.__defaultEntryTextColor)
        else:
            self.__entImapPort.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#FF0000"))
            
        if condition3:
            self.__entSmtpPort.modify_text(gtk.STATE_NORMAL, self.__defaultEntryTextColor)
        else:
            self.__entSmtpPort.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#FF0000"))

        self.__butOk.set_sensitive(condition1 and condition2 and condition3)
        
    def butclearalldata_clicked(self, widget):
        self.__clear_data()
